<template>
  <HeadContainer :title="$t('title.fanSendSet')" @back="back">
    <div class="gap-row-16 d-flex align-center justify-space-between">
      <div>
        {{ $t('label.fanSendSet.para1_1') }}<span class="text-primary">{{ $t('label.fanSendSet.para1_2') }}</span
        >{{ $t('label.fanSendSet.para1_3') }}
      </div>
      <div class="mr-1">
        <InputSwitch @click="getIsSent" :inputBg="'defaultBg'" v-model="isSent"></InputSwitch>
      </div>
    </div>
    <div v-if="isSent">
      <div class="gap-col-8">
        <div class="d-flex justify-space-between align-center mt-3 mb-2">
          <p>
            {{ $t('label.fanSendSet.para2_1')
            }}<span class="font-size-14 font-weight-400 line-height-120 text-graydisabled"
              >({{ $t('label.fanSendSet.para2_1') }})</span
            >
          </p>
          <p class="font-size-12 font-weight-400">
            {{ selectedArray.length }}<span class="text-graydisabled">/10</span>
          </p>
        </div>
        <div v-if="selectedArray.length > 0" @click="toggleEye" class="d-flex justify-end mt-2">
          <Icon v-if="isHidden" name="hide"></Icon>
          <Icon v-if="!isHidden" name="eye"></Icon>
        </div>
        <div class="gap-col-10">
          <div class="gap-row-8 d-flex mediaList" v-for="(item, index) in selectedArray" :key="`media-item-${index}`">
            <div class="mediaList-img">
              <div :class="{ mask: isHidden }">
                <div v-if="isHidden">
                  <div v-if="item.content.mv_money > 0">
                    <div class="money">
                      <div class="text-white font-size-16 font-style-normal font-weight-500 line-height-100">$</div>
                      <div class="text-white font-size-26 font-style-normal font-weight-500 line-height-100">
                        {{ item.content.mv_money }}
                      </div>
                    </div>
                  </div>
                  <div v-if="item.content.mv_money === 0"><Icon size="54" name="lock2"></Icon></div>
                </div>
              </div>
              <EncryptImage class="border-10" :src="item.content.mv_img_path" object-fit="cover"></EncryptImage>
              <div @click="handleRemoveItem(item)" class="close-btn">
                <Icon size="20" name="close"></Icon>
              </div>
              <div v-if="item.content.mv_type === MEDIA_TYPE.VIDEO" class="video-time font-size-10">
                {{ transDuration(item.content.mv_time) }}
              </div>
            </div>
            <div class="mediaList-cnt">
              <TextareaWrap
                v-model="item.content.content"
                heightFull
                :placeholder="$t('placeholder.message')"
                :line="7"
              ></TextareaWrap>
            </div>
          </div>
        </div>
        <button
          @click="emits('toPage', `select-media`, fanSendSetTurnOn)"
          class="cancel-light-btn border-10 full w-100 d-flex align-center justify-center"
        >
          <Icon class="mr-2" name="add"></Icon>
          {{ $t('label.addPushMsg') }}
        </button>
      </div>
      <v-divider class="my-4"></v-divider>
      <div class="mt-4">
        <div class="d-flex gap-row-16">
          <div @click="back" class="cancel-btn bg-gray-x w-100 d-flex justify-center align-center">
            {{ $t('common.back') }}
          </div>
          <div @click="onSubmit()" class="primary-btn w-100 d-flex justify-center align-center">
            {{ $t('common.save') }}
          </div>
        </div>
      </div>
    </div>
  </HeadContainer>
</template>
<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useFanSendSet } from '@/store/fan-send-set.js'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { repairZero } from '@/utils/string-helper'
import InputSwitch from '@/components/form/InputSwitch.vue'
import TextareaWrap from '@/components/form/TextareaWrap.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import EncryptImage from '@/components/multimedia/EncryptImage.vue'
import { MEDIA_TYPE } from '@/constant'
import API from '@/http'

const fanSendSetStore = useFanSendSet()
const { removeSelectItem, refreshPushList } = fanSendSetStore
const { isSent, selectedArray, initList, isTrigger, pushListId } = storeToRefs(fanSendSetStore)
const { open } = usePopupMessageStore()
const accountStore = useAccountStore()
const { userData } = storeToRefs(accountStore)
const { $confirm } = usePopupDialogStore()

const emits = defineEmits(['toPage', 'back'])
function back() {
  emits('back')
}

const getIsSent = async () => {
  try {
    if (isSent.value) {
      await API.Auth.update({ data: { push_button: false } })
      isSent.value = false
    } else {
      await API.Auth.update({ data: { push_button: true } })
      isSent.value = true
    }
  } catch (error) {
    console.error(error)
  }
}
watch(userData, (newUserData) => {
  if (newUserData.push_button === true) {
    isSent.value = true
  } else {
    isSent.value = false
  }
})

watch(isTrigger, (val) => {
  if (!val) return
  refreshPushList()
})
onMounted(refreshPushList)

const isHidden = ref(true)
const toggleEye = () => {
  isHidden.value = !isHidden.value
  console.log(selectedArray)
}

function transDuration(videoTime) {
  if (!videoTime) return '00:00'
  return `${repairZero(parseInt(videoTime / 60))}:${repairZero(videoTime % 60)}`
}

const handleRemoveItem = (item) => {
  removeSelectItem(item)
}

const newArray = computed(() => {
  return Array.from(selectedArray.value).map((item) => {
    return {
      mv_id: item.content.mv_id,
      content: item.content.content,
    }
  })
})

const onSubmit = () => {
  console.log(newArray.value, '要傳去後端的 newArray 陣列長這樣')
  $confirm({
    title: $t('content.saveCfm'),
    content: $t('content.changesSave'),
    confirm: () => {
      apiRequest()
    },
    cancel: () => {
      console.log('按下取消')
    },
    fromCenter: false,
  }).open()
}

const apiRequest = () => {
  if (pushListId.value) {
    console.log(`有id, 要update, 你的id是 ${initList.value.id}`)
    if (newArray.value.length === 0) {
      open($t('info.pushMsgLeast'))
    } else if (newArray.value.length > 0) {
      console.log('推播訊息有1則以上，可發布')
      API.Creator.pushupdate({
        data: {
          id: initList.value.id,
          content: newArray.value,
        },
      })
        .then((response) => {
          console.log('後端傳送成功', response)
          open($t('content.publish.createSuccess'))
        })
        .catch((error) => {
          console.log('沒傳送到後端', error)
        })
    }
  } else {
    console.log('沒有id, 要create')
    console.log(newArray.value.length)
    if (newArray.value.length === 0) {
      open($t('info.pushMsgLeast'))
    } else if (newArray.value.length > 0) {
      console.log('推播訊息有1則以上，可發布')
      API.Creator.pushcreate({
        data: {
          content: newArray.value,
        },
      })
        .then((response) => {
          console.log('後端傳送成功', response)
          open($t('content.publish.createSuccess'))
        })
        .catch((error) => {
          console.log('沒傳送到後端', error)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.border-10 {
  border-radius: 0.625rem;
}

.cancel-light-btn {
  padding: 0.5625rem 1rem;
  border-radius: 0.625rem;
}

.mediaList {
  height: 10.3125rem;
  &-img {
    width: 10.3125rem;
    position: relative;
    & .mask {
      width: 100%;
      height: 10.3125rem;
      border-radius: 10px;
      position: absolute;
      top: 0;
      background: linear-gradient(180deg, rgba(249, 94, 14, 0.2) -40%, rgba(231, 23, 179, 0.2) 112.5%);
      backdrop-filter: blur(4px);
      display: flex;
      justify-content: center;
      align-items: center;
    }

    & .money {
      display: flex;
      justify-content: center;
      text-align: center;
      align-items: center;
    }

    & .video-time {
      position: absolute;
      bottom: 0;
      padding: 5px 8px;
    }

    .border {
      border-radius: 10px;
    }

    .close-btn {
      position: absolute;
      top: 0;
      right: 0;
      padding: 0.5rem;
      cursor: pointer;
    }
  }

  &-cnt {
    width: 100%;
  }
}
</style>
